//
//  news.m
//  ios_news
//
//  Created by Han on 14-6-11.
//  Copyright (c) 2014年 ucoder. All rights reserved.
//

#import "NewsDetail.h"
#import "Util.h"

@implementation NewsDetail


- (instancetype)initWithAttributes:(NSDictionary *)attributes {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    self.nid = (NSUInteger)[[attributes valueForKeyPath:@"nid"] integerValue];
    self.title = [attributes valueForKeyPath:@"title"];
    self.name = [attributes valueForKeyPath:@"name"];
    
    self.date = [Util getDateFromTimestamp:[attributes valueForKeyPath:@"date"]];
    self.body = [attributes valueForKeyPath:@"body"];
    self.newsRelated = [attributes valueForKeyPath:@"newsRelated"];
    
    //self.user = [[User alloc] initWithAttributes:[attributes valueForKeyPath:@"user"]];
    return self;
}


+ (NSURLSessionDataTask *)getDataWithBlock:(void (^)(NewsDetail *posts, NSError *error))block :(NSString *) url {
    AFHTTPSessionManager *sharedClient = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:url]];
    sharedClient.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    
    return [sharedClient GET:@"" parameters:nil success:^(NSURLSessionDataTask * __unused task, id JSON) {
        
        NSArray *responseData = JSON;  // [JSON valueForKeyPath:@"data"]
        //NSLog(@"%@", responseData);
        NSDictionary *attributes;
        NSString *nid   = [responseData valueForKey:@"nid"];
        NSString *title = [responseData valueForKey:@"title"];
        NSString *name  = [responseData valueForKey:@"name"];
        NSString *date  = [responseData valueForKey:@"created"];
        NSArray *body  = [[responseData valueForKey:@"body"] valueForKey:@"und"];
        //NSString *summary  = [[[responseData valueForKey:@"body"] valueForKey:@"und"] valueForKey:@"safe_summary"];
        NSArray *related  = [responseData valueForKey:@"field_related"];
        
        // 相关文章
        NSArray *newsRelated;
        if ([related count] != 0) {
            newsRelated = [related valueForKey:@"und"];
        }
        
        
        attributes = [NSDictionary dictionaryWithObjectsAndKeys:nid, @"nid", title, @"title", name, @"name", date, @"date", [body[0] valueForKey:@"safe_value"], @"body", newsRelated, @"newsRelated", nil];
        
        NewsDetail *newsDetail = [[NewsDetail alloc] initWithAttributes:attributes];
        
        if (block) {
            block(newsDetail, nil);
        }
        
        
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        if (block) {
            NewsDetail *news;
            block(news, error);
        }
    }];
}

@end
